package cn.edu.nwpu.warehousemanagement.service.impl;

import cn.edu.nwpu.warehousemanagement.dao.InventoryConfigRepository;
import cn.edu.nwpu.warehousemanagement.pojo.InventoryConfig;
import cn.edu.nwpu.warehousemanagement.pojo.Result;
import cn.edu.nwpu.warehousemanagement.pojo.dto.PageDTO;
import cn.edu.nwpu.warehousemanagement.service.InventoryConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 库存配置服务实现
 * @author LSR
 */
@Service
@RequiredArgsConstructor
public class InventoryConfigServiceImpl implements InventoryConfigService {

    private final InventoryConfigRepository inventoryConfigRepository;

    @Override
    @Transactional
    public Result<InventoryConfig> create(InventoryConfig config) {
        try {
            // 检查商品是否已存在未删除的配置
            if (inventoryConfigRepository.existsByProductIdAndDeletedFalse(config.getProduct().getId())) {
                return Result.error("该商品已存在库存配置");
            }

            config.setDeleted(false);
            InventoryConfig savedConfig = inventoryConfigRepository.save(config);
            return Result.success(savedConfig);
        } catch (Exception e) {
            return Result.error("创建库存配置失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> delete(Long id) {
        try {
            Optional<InventoryConfig> config = inventoryConfigRepository.findByIdAndDeletedFalse(id);
            if (config.isEmpty()) {
                return Result.error("库存配置不存在或已被删除");
            }
            inventoryConfigRepository.softDeleteById(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error("删除库存配置失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> deleteByProductId(Long productId) {
        try {
            Optional<InventoryConfig> config = inventoryConfigRepository.findByProductIdAndDeletedFalse(productId);
            if (config.isEmpty()) {
                return Result.error("库存配置不存在或已被删除");
            }
            inventoryConfigRepository.softDeleteById(config.get().getId());
            return Result.success();
        } catch (Exception e) {
            return Result.error("删除库存配置失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<InventoryConfig> update(InventoryConfig config) {
        try {
            if (config.getId() == null) {
                return Result.error("ID不能为空");
            }

            // 检查记录是否存在且未删除
            Optional<InventoryConfig> existingConfig = inventoryConfigRepository.findByIdAndDeletedFalse(config.getId());
            if (existingConfig.isEmpty()) {
                return Result.error("库存配置不存在或已被删除");
            }

            // 更新记录
            config.setDeleted(false);
            InventoryConfig updatedConfig = inventoryConfigRepository.save(config);
            return Result.success(updatedConfig);
        } catch (Exception e) {
            return Result.error("更新库存配置失败: " + e.getMessage());
        }
    }

    @Override
    public Result<InventoryConfig> getById(Long id) {
        try {
            Optional<InventoryConfig> config = inventoryConfigRepository.findByIdAndDeletedFalse(id);
            return config.map(Result::success)
                    .orElseGet(() -> Result.error("库存配置不存在或已被删除"));
        } catch (Exception e) {
            return Result.error("查询库存配置失败: " + e.getMessage());
        }
    }

    @Override
    public Result<InventoryConfig> getByProductId(Long productId) {
        try {
            Optional<InventoryConfig> config = inventoryConfigRepository.findByProductIdAndDeletedFalse(productId);
            return config.map(Result::success)
                    .orElseGet(() -> Result.error("该商品没有库存配置"));
        } catch (Exception e) {
            return Result.error("查询库存配置失败: " + e.getMessage());
        }
    }

    @Override
    public Result<Page<InventoryConfig>> listByPage(PageDTO pageDTO) {
        try {
            Pageable pageable = PageRequest.of(pageDTO.getPageNum() - 1, pageDTO.getPageSize());
            Page<InventoryConfig> page = inventoryConfigRepository.findByDeletedFalse(pageable);
            return Result.success(page);
        } catch (Exception e) {
            return Result.error("分页查询库存配置失败: " + e.getMessage());
        }
    }

    @Override
    public Result<List<InventoryConfig>> getAllInventoryConfigList() {
        try {
            List<InventoryConfig> allConfigs = inventoryConfigRepository.findByDeletedFalse();
            return Result.success(allConfigs);
        } catch (Exception e) {
            return Result.error("获取所有库存配置列表失败: " + e.getMessage());
        }
    }

    @Override
    public Result<List<Page<InventoryConfig>>> getAllInventoryConfigPages() {
        try {
            List<Page<InventoryConfig>> allPages = new ArrayList<>();
            int pageNum = 1;
            boolean hasMore = true;

            while (hasMore) {
                Pageable pageable = PageRequest.of(pageNum - 1, 20);
                Page<InventoryConfig> page = inventoryConfigRepository.findByDeletedFalse(pageable);
                allPages.add(page);

                if (pageNum >= page.getTotalPages()) {
                    hasMore = false;
                }
                pageNum++;
            }

            return Result.success(allPages);
        } catch (Exception e) {
            return Result.error("获取所有库存配置分页失败: " + e.getMessage());
        }
    }
}